package com.mojian.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mojian.entity.PointsRecord;
import com.mojian.entity.UserPoints;
import com.mojian.exception.ServiceException;
import com.mojian.mapper.PointsRecordMapper;
import com.mojian.mapper.UserPointsMapper;
import com.mojian.service.PointsService;
import com.mojian.utils.PageUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 积分服务实现类
 */
@Service
@RequiredArgsConstructor
public class PointsServiceImpl implements PointsService {

    private final UserPointsMapper userPointsMapper;
    private final PointsRecordMapper pointsRecordMapper;

    @Override
    public UserPoints getUserPoints() {
        Long userId = StpUtil.getLoginIdAsLong();
        UserPoints userPoints = userPointsMapper.selectOne(
            new LambdaQueryWrapper<UserPoints>().eq(UserPoints::getUserId, userId)
        );
        
        // 如果用户没有积分记录，创建一个初始记录
        if (userPoints == null) {
            userPoints = new UserPoints();
            userPoints.setUserId(userId);
            userPoints.setPoints(0);
            userPoints.setTotalEarned(0);
            userPoints.setTotalConsumed(0);
            userPointsMapper.insert(userPoints);
        }
        
        return userPoints;
    }

    @Override
    public Page<PointsRecord> getPointsRecords(Integer pageNum, Integer pageSize) {
        Long userId = StpUtil.getLoginIdAsLong();
        Page<PointsRecord> page = new Page<>(pageNum, pageSize);
        return pointsRecordMapper.getPointsRecords(page, userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addPoints(Long userId, Integer points, Integer type, Long relatedId, String description) {
        if (points <= 0) {
            throw new ServiceException("积分必须大于0");
        }
        
        // 获取用户积分信息
        UserPoints userPoints = getUserPointsByUserId(userId);
        
        // 更新用户积分
        userPoints.setPoints(userPoints.getPoints() + points);
        userPoints.setTotalEarned(userPoints.getTotalEarned() + points);
        userPointsMapper.updateById(userPoints);
        
        // 记录积分变动
        PointsRecord record = new PointsRecord();
        record.setUserId(userId);
        record.setPoints(points);
        record.setBalance(userPoints.getPoints());
        record.setType(type);
        record.setRelatedId(relatedId);
        record.setDescription(description);
        pointsRecordMapper.insert(record);
        
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean consumePoints(Long userId, Integer points, Integer type, Long relatedId, String description) {
        if (points <= 0) {
            throw new ServiceException("积分必须大于0");
        }
        
        // 获取用户积分信息
        UserPoints userPoints = getUserPointsByUserId(userId);
        
        // 检查积分是否足够
        if (userPoints.getPoints() < points) {
            throw new ServiceException("积分不足");
        }
        
        // 更新用户积分
        userPoints.setPoints(userPoints.getPoints() - points);
        userPoints.setTotalConsumed(userPoints.getTotalConsumed() + points);
        userPointsMapper.updateById(userPoints);
        
        // 记录积分变动
        PointsRecord record = new PointsRecord();
        record.setUserId(userId);
        record.setPoints(-points); // 消费为负数
        record.setBalance(userPoints.getPoints());
        record.setType(type);
        record.setRelatedId(relatedId);
        record.setDescription(description);
        pointsRecordMapper.insert(record);
        
        return true;
    }

    @Override
    public boolean signInReward(Long userId) {
        // 签到奖励10积分
        return addPoints(userId, 10, 1, null, "每日签到奖励");
    }

    @Override
    public boolean hasEnoughPoints(Long userId, Integer points) {
        UserPoints userPoints = getUserPointsByUserId(userId);
        return userPoints.getPoints() >= points;
    }
    
    /**
     * 根据用户ID获取积分信息
     */
    private UserPoints getUserPointsByUserId(Long userId) {
        UserPoints userPoints = userPointsMapper.selectOne(
            new LambdaQueryWrapper<UserPoints>().eq(UserPoints::getUserId, userId)
        );
        
        // 如果用户没有积分记录，创建一个初始记录
        if (userPoints == null) {
            userPoints = new UserPoints();
            userPoints.setUserId(userId);
            userPoints.setPoints(0);
            userPoints.setTotalEarned(0);
            userPoints.setTotalConsumed(0);
            userPointsMapper.insert(userPoints);
        }
        
        return userPoints;
    }
} 